import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

import { CallHandler, ExecutionContext, HttpStatus, Injectable, NestInterceptor } from '@nestjs/common';
import { Response } from 'express';

const WHILE_LIST = [];

@Injectable()
export class RenderInterceptor<T> implements NestInterceptor<T, Response<T>> {
  intercept(context: ExecutionContext, next: CallHandler): Observable<Response<T>> {
    const request = context.switchToHttp().getRequest();
    const response = context.switchToHttp().getResponse<Response>();

    const base = { message: 'OK', code: HttpStatus.OK, success: true };
    return next.handle().pipe(
      map((data) => {
        if (WHILE_LIST.includes(request.path)) {
          return data;
        }
        const disposition = response.getHeader('content-disposition');
        if (disposition === 'attachment') {
          return data;
        }
        if (data?.message && data?.code) return data;
        return data?.data ? { ...data, ...base } : { data, ...base };
      }),
    );
  }
}
